﻿namespace EAL.Misc
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using EAL.Models;

    /// <summary>
    /// Klasse zum Handhaben der csvdateien
    /// 
    /// </summary>
    /// <remarks>Author : Jan Scheffler
    ///                   Felix Liebmann
    ///                   Martin Kuschnik
    /// </remarks>
    public class CsvHandler
    {
        public static void writeCsv<T>(String path, IEnumerable<T> items) where T : ICsvSerializable
        {
            using (StreamWriter sw = new StreamWriter(new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write)))
            {
                foreach (ICsvSerializable item in items)
                {
                    sw.WriteLine(item.ToCsvLine());
                }                   
            }
        }

        public static IEnumerable<T> readCsv<T>(String path) where T : ICsvSerializable
        {
            List<T> resultList = new List<T>();
            using (StreamReader sr = new StreamReader(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)))
            {
                while (!sr.EndOfStream)
                {
                    resultList.Add((T)(Activator.CreateInstance(typeof(T)) as ICsvSerializable).FromCsvLine(sr.ReadLine()));
                }
            }

            return resultList;
        }
    }
}
